import React, { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"

import "./index.less"
import { useModel } from "umi";
import { getAllParentData, getChild, handleStr } from '@/utils';
import { DevPopup } from '~/public/cpas-ui';
import { columns } from "./SimpleDatas";
import type { guid } from 'guid-factory/lib/Guid';
import { Guid } from 'guid-factory/lib/Guid';
import notify from "devextreme/ui/notify";
import { LoadIndicator, TreeList } from "devextreme-react";
import PhaseDeleteDialog from '@/pages/components/ProjectTreeTabsComponent/PhaseDeleteDialog';
import SubjectPopupData from '@/pages/components/ProjectTreeTabsComponent/components/SubjectsPopup';
import AuxiliaryPopup from '@/pages/components/ProjectTreeTabsComponent/components/AuxiliaryPopup';
import {
    Addsubject, AssistAdd, AssistDel, AssistEdit, AssistgetType,
    AutoAddChildrenForFZZ, Editsubject, getNewKMBH, IsCanAddFZZ, SubjectDel, SubjectIsHasFZZ
} from '@/pages/components/ProjectTreeTabsComponent/service';
import { getAccountInfo, getSubjectList, getSubjectParentList, getSubjectType } from './service';
import AntTabs, { HocVerticalLeftStyleTab } from "~/public/cpas-ui/components-ui/ant-components/AntTab";
import FirstLevelSubjectPopup from "@/pages/components/ProjectTreeTabsComponent/components/FirstLevelSubjectPopup";
import { deepClone } from "~/public/cpas-business/tools/Tools";
import { nanoid10 } from "@/utils";
import { SpecificPupopContext } from '../../../SpecificPupopFun';


const AdjustLeftTree = React.forwardRef((props: any, ref: any) => {
    const { treeSelectCellClick, treeNodeCellDblClick, whereFrom } = props;
    // const { setIsShowGlobalLoad } = useModel('useAdjustModel');

    const { entryParamData } = useContext<any>(SpecificPupopContext);
    const { curDataYearData_ID: AccountDataID, curDataBillID } = entryParamData;

    const { initialState } = useModel('@@initialState');
    const { username } = initialState?.curUser;
    const { dbname } = initialState?.curPart;
    // const ParentLevel = useRef<any>()
    const curNodeRef = useRef<any>();
    const typeRef = useRef<any>();
    const typeErrorRef = useRef<any>();
    const TreeListRef = useRef<any>();
    const FirstLevelSubjectPopupRef = useRef<any>();//快速新增一级科目
    const PhaseDeleteRef = useRef<any>();
    const SubjectPopupRef = useRef<any>();
    const AuxiliaryPopupRef = useRef<any>();
    const TreeAuxiliaryRef = useRef<any>();
    const [isShowRightTree, setIsShowRightTree] = useState<boolean>(false);


    const [AddFZZKMMC, setIsCanAddFZZKMMC] = useState<string>('');

    const [entryTabsData, setEntryTabsData] = useState<any[]>([]);
    const [tbsStates, setTbsStates] = useState<any>('0');

    const tbsStatesRef = useRef<string>('0');


    const [curRowKMMC, setCurRowKMMC] = useState<string>("");

    const [startupSelectedKeys, setStartupSelectedKeys] = useState<any>([]);


    const [entryFilterTreeData, setEntryFilterTreeData] = useState<any[]>([]);// 树的过滤数据
    const entryTreeDataRef = useRef<any>();
    const [visiblePopupKey, setVisiblePopupKey] = useState<string>('');

    const getSubjectTypeData = async (DataId: any) => {
        const res = await getSubjectType({
            dbname,
            Data_ID: DataId,
        });
        if (res.success) {
            res.data.unshift({ code: "0", type: "全部" });
            setEntryTabsData(res.data);
            console.log(res.data, '@@@');
            setTbsStates('0');
            tbsStatesRef.current = '0';
        }
    };

    // 右侧 切换方法
    const getSubjectListData = useCallback(async (r: string, isChangeKey: boolean = false) => {
        const resF = entryTabsData.filter((item: any) => r === item.code);
        const filStr = resF[0]?.type ?? '全部';
        setTbsStates(r);
        tbsStatesRef.current = r;
        if (isChangeKey) {
            setVisiblePopupKey(nanoid10());
        }
        if (entryTreeDataRef.current?.length) {
            if (filStr === "全部") {
                setEntryFilterTreeData(entryTreeDataRef.current);
            } else {
                const KMLXData = entryTreeDataRef.current.filter((item: any) => {
                    return item.KMLX && item.KMLX.includes(filStr)
                });
                setEntryFilterTreeData(KMLXData);
            }
        }
    }, [entryTreeDataRef.current, entryTabsData]);
    // 获取树表格数据 设置属性的时候
    const getSubjectListDatas = async (DataId: any) => {
        setIsShowRightTree(true);
        if (TreeListRef.current) {
            TreeListRef.current.instance.clearSelection();
        }

        entryTreeDataRef.current = [];
        const res = await getSubjectList({
            dbname,
            Data_ID: DataId,
            isHasFZZ: true,
        });
        if (res.success) {
            // setEntryFilterTreeData(res.data);
            entryTreeDataRef.current = res.data;
            if (res.data?.length) {
                console.log(tbsStatesRef.current, 'e @@@');
                getSubjectListData(tbsStatesRef.current);
            }
        }

    };

    useEffect(() => {
        if (AccountDataID) {
            setStartupSelectedKeys([]);
            setTbsStates('0');
            tbsStatesRef.current = '0';
            getSubjectTypeData(AccountDataID);
            getSubjectListDatas(AccountDataID);
            setVisiblePopupKey(nanoid10());
        }
    }, [AccountDataID]);


    const saveAddsubject = async (tempObj: any, isAddMoreYear: boolean) => {
        if (!isAddMoreYear) {
            const res = await Addsubject(tempObj);
            if (res.ok) {
                notify("增加科目成功", 'success', 2000);
                getSubjectListDatas(AccountDataID);
            }
            return;
        }
        const resYear: any = await getAccountInfo({ dbname });
        if (resYear.success) {
            const yearData = resYear.data.map((item: any) => item.Data_ID);
            const tempA: any = [];
            for (let index = 0; index < yearData.length; index++) {
                const element = yearData[index];
                if (element) {
                    const res = await Addsubject({ ...tempObj, Data_ID: element });
                    if (res.ok && res.data > 0) {
                        tempA.push(Promise.resolve('ok'));
                    } else {
                        tempA.push(Promise.resolve(`${element}年:${res.data}`));
                    }
                }
            }
            Promise.allSettled(tempA).then(results => {
                console.log(tempA, results, '@@@');
                getSubjectListDatas(AccountDataID);

                const falseData = results.filter((item1: any) => item1.value !== 'ok').map((item: any) => item.value);
                if (falseData.length) {
                    // notify(`增加科目失败，失败原因为【${falseData.join(';')};】`, falseData.length === yearData.length ? 'error' : 'warning', 2000);
                    notify(`增加科目失败，失败原因为【${falseData.join(';')};】`, 'warning', 2000);
                } else {
                    notify("增加科目成功", 'success', 2000);
                }
            }).catch(error => {
                // 处理错误
                console.error("An error occurred:", error);
            });

        } else {
            notify(`获取年度失败！`, 'error', 2000);
        }
    }
    // 判断 是否为 66为辅助类型 99辅助账
    const subjectMethod = (e: any, r: any) => {
        const itemNames = r.selectedYears || '';
        let tempObj = {};

        if (e) {
            //r ? 有返回参数 说明他有上级科目 : 说明它是增加一级科目
            tempObj = {
                dbname,
                Data_ID: AccountDataID,
                KMBH: r.KMBH ? r.KMBH : r.KMBHAdd + '~|',
                KMMC: r.KMMC ? r.KMMC + '-' + r.SubjectNumber : r.SubjectNumber,
                editUser: username,
                PKMBH: r.PKMBH,
                YSKMBH: `${r.KMBHAdd}`,
                YSKMMC: r.SubjectNumber,
                KMFX: r.SelectName,
                KMLX: r.SelectType,
                JC: r.Satatejc ? Number(r.Satatejc) + 1 : 1,
                itemNames: itemNames,
                checkBoxState: r.checkBoxState
            }
            console.log(tempObj, '@@@');
            saveAddsubject(tempObj, r.checkBoxState);
        }
    }
    const saveAssistAdd = async (dataObj: any, isAddMoreYear: any) => {
        if (!isAddMoreYear) {
            const data = await AssistAdd(dataObj);
            if (data.ok) {
                notify("增加辅助账成功", 'success', 2000);
                getSubjectListDatas(AccountDataID);
            }
            else {
                notify('该科目下已存在相同名称的辅助核算项目，无法重复新增！', 'error', 2000)
            }
            return;
        }
        const resYear: any = await getAccountInfo({ dbname });
        if (resYear.success) {
            const yearData = resYear.data.map((item: any) => item.Data_ID);
            const tempA: any = [];
            for (let index = 0; index < yearData.length; index++) {
                const element = yearData[index];
                if (element) {
                    const res = await AssistAdd({ ...dataObj, Data_ID: element });
                    if (res.ok && res.data > 0) {
                        tempA.push(Promise.resolve('ok'));
                    } else {
                        tempA.push(Promise.resolve(`${element}年:${res.data}`));
                    }
                }
            }
            Promise.allSettled(tempA).then(results => {
                console.log(tempA, results, '@@@');
                getSubjectListDatas(AccountDataID);

                const falseData = results.filter((item1: any) => item1.value !== 'ok').map((item: any) => item.value);
                if (falseData.length) {
                    // notify(`增加科目失败，失败原因为【${falseData.join(';')};】`, falseData.length === yearData.length ? 'error' : 'warning', 2000);
                    notify(`增加科目失败，失败原因为【${falseData.join(';')};】`, 'warning', 2000);
                } else {
                    notify("增加辅助账成功", 'success', 2000);
                }
            }).catch(error => {
                // 处理错误
                console.error("An error occurred:", error);
            });

        } else {
            notify(`获取年度失败！`, 'error', 2000);
        }
    }


    const openAuxiliaryPopup = (tmepArgs: any, tmepBH: any, tempRowData: any) => {
        let tempObj: any = {
            dbname,
            Data_ID: AccountDataID,
            editUser: username,
        };
        AuxiliaryPopupRef.current.show({
            args: tmepArgs,
            okCallback: (v: any) => {
                tempObj = {
                    ...tempObj,
                    KMBH: v.KMBH ? v.KMBH : tempRowData.KMBH,
                    KMMC: v.KMMC ? v.KMMC : tempRowData.KMMC,
                    HSXMLXBH: v.SelectHSXMLXBH,
                    YSKMBH: `${v.YSKMBH}` ? `${v.YSKMBH}` : `${tmepBH}`,
                    HSXMLXMC: v.selectValue,
                    HSXMBH: v.SelectHSXMLXBH + '-' + v.projectValueMds + '~|',
                    HSXMMC: v.projectValues,
                    YSHSXMMC: v.projectValues,
                    YSHSXMBH: v.SelectHSXMLXBH + '-' + v.projectValueMds
                };
                saveAssistAdd(tempObj, v.checkBoxState);
            },
            cancelCallback: () => {

            }
        });
    }



    const menuAddsubjectFunc = async (rowData: any) => {
        const MatchKMMC = rowData.KMMC.match(/(\S*)-/);
        let tabsArray = [...entryTabsData];
        tabsArray.shift();
        if (rowData.JC === 1) {
            SubjectPopupRef.current.show({
                args: {
                    title: '新增科目',
                    KMBH: "",
                    data: tabsArray,
                    ParentLevel: '',
                    ParentLevelKmbh: "",
                    PKMBH: '',
                    resolvess: rowData.KMMC,
                    datatKMFX: rowData.KMFX,
                    dataKMLX: rowData.KMLX,
                    isEdit: false,
                },
                okCallback: (r: any) => {
                    console.log(r, '@@@ 新增科目');
                    if (r) {
                        const itemNames = r.selectedYears || '';
                        let tempObj: any = {
                            dbname,
                            Data_ID: AccountDataID,
                            editUser: username,
                            YSKMBH: `${r.KMBHAdd}`,
                            YSKMMC: r.SubjectNumber,
                            KMFX: r.SelectName,
                            KMLX: r.SelectType,
                            itemNames: itemNames,
                            KMBH: r.KMBH ? r.KMBH : r.KMBHAdd + '~|',
                        };
                        if (r.Satatejc) {
                            tempObj = {
                                ...tempObj,
                                KMMC: r.KMMC + '-' + r.SubjectNumber,
                                PKMBH: r.PKMBH,
                                JC: Number(r.Satatejc) + 1,
                            }
                        } else {
                            tempObj = {
                                ...tempObj,
                                KMMC: r.SubjectNumber,
                                PKMBH: "",
                                JC: rowData.JC,
                            }
                        }
                        console.log(r, tempObj, '@@@ 这是新增科目tempObj');

                        saveAddsubject(tempObj, r.checkBoxState);
                    }
                },
                cancelCallback: () => {
                }
            });
            return;
        }
        if (rowData.ZWType === 1) {
            // const eKMMC = curNodeRef.current.KMMC.match(/(\S*)-/);
            // 判断 是否为 66为辅助类型 99辅助账
            if (rowData.level === 66) {
                // 在辅助类型上 增加 科目参数传递有误
                typeRef.current.show({
                    title: "提示",
                    okCallback: () => {
                        typeErrorRef.current.show({
                            title: "提示",
                            okCallback: () => {
                                // 后期在业务组件里面做判断
                                SubjectPopupRef.current.show({
                                    args: {
                                        title: '新增科目',
                                        KMBH: "",
                                        data: tabsArray,
                                        ParentLevel: '',
                                        ParentLevelKmbh: "",
                                        PKMBH: '',
                                        resolvess: '',
                                        datatKMFX: rowData.KMFX,
                                        dataKMLX: rowData.KMLX,
                                        isEdit: false,
                                    },
                                    okCallback: (r: any) => {
                                        subjectMethod(MatchKMMC, r);
                                    },
                                    cancelCallback: () => {

                                    }
                                });
                            }
                        });
                    }
                });
                return;
            }
            if (rowData.level === 99) {
                // 在辅助账数据上 增加 科目参数传递有误
                SubjectPopupRef.current.show({
                    args: {
                        title: '新增科目',
                        KMBH: "",
                        data: tabsArray,
                        ParentLevel: '',
                        ParentLevelKmbh: "",
                        PKMBH: '',
                        resolvess: '',
                        datatKMFX: rowData.KMFX,
                        dataKMLX: rowData.KMLX,
                        isEdit: false,
                    },
                    okCallback: (r: any) => {
                        console.log(r, '--rrr-----rrrr辅助帐增加科目');

                        subjectMethod(MatchKMMC, r);

                    },
                    cancelCallback: () => {

                    }
                });
            }
            return;
        }
        console.log(rowData, 'data----');
        let parentLevelName = '';
        let resolvess = '';
        if (rowData.PKMBH) {
            const res = await getSubjectParentList({ dbname, Data_ID: AccountDataID, PKMBH: rowData.PKMBH });
            if (res.success) {
                const { data } = res;
                parentLevelName = data.displayName;
                resolvess = data.KMMC;
            }
        }
        const RNewKMBH = await getNewKMBH({
            dbname,
            Data_ID: AccountDataID,
            KMBH: rowData.PID
        });
        SubjectPopupRef.current.show({
            args: {
                title: '新增科目',
                KMBH: RNewKMBH.data[0].KMBH,
                data: tabsArray,
                ParentLevel: parentLevelName,
                ParentLevelKmbh: RNewKMBH.data[0].YSKMBH,
                PKMBH: rowData.PKMBH,
                resolvess,
                datatKMFX: rowData.KMFX,
                dataKMLX: rowData.KMLX,
                isEdit: false,
            },
            okCallback: (r: any) => {
                console.log(r, '------');
                // 修改 变动
                const itemNames = r.selectedYears || '';
                let dataObj = {};
                // 如果 他的上级科目被删除了 执行下方方法
                if (r.PKMBHState) {
                    dataObj = {
                        dbname,
                        Data_ID: AccountDataID,
                        KMBH: r.KMBH ? r.KMBH : r.KMBHAdd + '~|',
                        KMMC: r.SubjectNumber,
                        editUser: username,
                        PKMBH: "",
                        YSKMBH: `${r.KMBHAdd}`,
                        YSKMMC: r.SubjectNumber,
                        KMFX: r.SelectName,
                        KMLX: r.SelectType,
                        JC: 1,
                        itemNames: itemNames,
                    }
                } else {
                    dataObj = {
                        dbname,
                        Data_ID: AccountDataID,
                        KMBH: r.KMBH ? r.KMBH : RNewKMBH.data[0].KMBH,
                        KMMC: `${r.KMMC ? r.KMMC : resolvess}-${r.SubjectNumber}`,
                        editUser: username,
                        PKMBH: r.PKMBH,
                        YSKMBH: `${r.KMBHAdd}`,
                        YSKMMC: r.SubjectNumber,
                        KMFX: r.SelectName,
                        KMLX: r.SelectType,
                        JC: r.Satatejc ? Number(r.Satatejc) + 1 : rowData.JC,
                        itemNames: itemNames,
                    }
                }
                console.log(r, dataObj, '@@@');

                // 
                saveAddsubject(dataObj, r.checkBoxState);

            },
            cancelCallback: () => {

            }
        });
    }
    // 判断是否可以增加辅助账
    const IsCanAddFZZStates = async (vData: any, isBoolean: boolean, vRowData: any) => {
        if (isBoolean) {
            const YSKMBH = handleStr(vRowData.KMBH);
            const r = await AssistgetType({
                dbname,
                Data_ID: AccountDataID,
                KMBH: vRowData.KMBH
            });
            openAuxiliaryPopup({
                title: '新增辅助账',
                value: YSKMBH + '-' + vRowData.KMMC,
                auxiliaryState: true,
                items: r,
                edit: false,
                fzzData: vRowData
            }, YSKMBH, vRowData);
            return;
        }
        const value = await AutoAddChildrenForFZZ({
            dbname,
            Data_ID: AccountDataID,
            KMBH: vRowData.KMBH,
            editUser: username
        });
        const r = await AssistgetType({
            dbname,
            Data_ID: AccountDataID,
            KMBH: value[0].KMBH,
        });
        const PKMBH = handleStr(value[0].KMBH);
        console.log(value, 'value---');
        if (vData.code === 1) {
            openAuxiliaryPopup({
                title: '新增辅助账',
                value: PKMBH + '-' + value[0].KMMC,
                auxiliaryState: true,
                items: r,
                edit: false,
                fzzData: vRowData
            }, PKMBH, vRowData);
            return;
        } else if (vData.code === 2) {
            setIsCanAddFZZKMMC(vData.message);
            TreeAuxiliaryRef.current.show({
                title: "提示",
                okCallback: () => {
                    openAuxiliaryPopup({
                        title: '新增辅助账',
                        value: PKMBH + '-' + value[0].KMMC,
                        auxiliaryState: true,
                        items: r,
                        edit: false,
                        fzzData: value[0]
                    }, PKMBH, vRowData);
                }
            });
            return;
        }
    }
    const menuEditsubjectFunc = async (rowData: any) => {
        const YSKMBH = handleStr(rowData.KMBH);
        const YSHSXMBH = handleStr(rowData.code);
        let tabsArray = [...entryTabsData];
        tabsArray.shift();
        if (rowData.ZWType === 1) {
            const r = await AssistgetType({
                dbname,
                Data_ID: AccountDataID,
                KMBH: rowData.KMBH
            });
            // 判断 是否为 66为辅助类型 99辅助账
            if (rowData.level === 66) {
                return openAuxiliaryPopup({
                    title: '新增辅助账',
                    value: YSKMBH + '-' + rowData.KMMC,
                    auxiliaryState: true,
                    items: r,
                    edit: false,
                    fzzData: rowData
                }, YSKMBH, rowData);
            }
            console.log(rowData, 'curNodeRef.current.KMBH---');
            if (rowData.isNewAdd) {


                return AuxiliaryPopupRef.current.show({
                    args: {
                        title: '编辑辅助账',
                        value: YSKMBH + '-' + rowData.KMMC,
                        auxiliaryState: true,
                        items: r,
                        edit: true,
                        HSXMMC: rowData.HSXMMC,
                        fzzData: rowData
                    },
                    okCallback: async (v: any) => {
                        const data = await AssistEdit({
                            dbname,
                            Data_ID: AccountDataID,
                            KMBH: rowData.KMBH,
                            KMMC: rowData.KMMC,
                            editUser: username,
                            HSXMLXBH: v.SelectHSXMLXBH,
                            YSKMBH: `${YSKMBH}`,
                            HSXMLXMC: v.selectValue,
                            HSXMBH: rowData.code + '~|',
                            HSXMMC: v.projectValue,
                            YSHSXMMC: v.projectValue,
                            YSHSXMBH: YSHSXMBH
                        })
                        if (data) {
                            notify("修改辅助账成功", 'success', 2000);
                            getSubjectListDatas(AccountDataID);

                        }
                    },
                    cancelCallback: () => {

                    }
                });
            }
            notify(`辅助账【${rowData.HSXMMC}】为企业原始辅助账,不可编辑`, 'warning', 2000)
            return;

        } else {
            console.log(rowData, "111111");
            // 编辑 科目
            if (rowData.isNewAdd) {

                console.log(rowData, '@@@ 编辑 科目');
                let parentLevelName = '';
                let resolvess = '';
                if (rowData.PKMBH) {
                    const res = await getSubjectParentList({ dbname, Data_ID: AccountDataID, PKMBH: rowData.PKMBH });
                    if (res.success) {
                        const { data } = res;
                        parentLevelName = data.displayName;
                        resolvess = data.KMMC;
                    }
                }
                SubjectPopupRef.current.show({
                    args: {
                        title: '编辑',
                        KMBH: rowData.KMBH,
                        data: tabsArray,
                        ParentLevel: rowData.JC === 1 ? "" : parentLevelName,
                        ParentLevelKmbh: Number(rowData?.YSKMBH || 0),
                        PKMBH: rowData.PKMBH,
                        KMMC: rowData.YSKMMC,
                        datatKMFX: rowData.KMFX,
                        dataKMLX: rowData.KMLX,
                        itemNames: rowData.itemNames,
                        resolvess,
                        isEdit: true,
                    },
                    okCallback: async (v: any) => {
                        console.log(resolvess, 'resolvess-----');
                        console.log("确定回调函数");
                        const itemNames = v.selectedYears || rowData.itemNames;
                        const tempKMMC = `${resolvess && resolvess + '-'}${v.SubjectNumber}`;
                        const r = await Editsubject({
                            dbname,
                            Data_ID: AccountDataID,
                            KMBH: rowData.KMBH,
                            KMMC: tempKMMC,
                            editUser: username,
                            YSKMMC: v.SubjectNumber,
                            KMFX: v.SelectName,
                            KMLX: v.SelectType,
                            itemNames: itemNames,
                        })
                        if (r.ok) {
                            notify("编辑科目成功", 'success', 2000);
                            getSubjectListDatas(AccountDataID);

                        }
                    },
                    cancelCallback: () => {

                    }
                });
            } else {
                notify(`科目【${rowData.KMMC}】为企业原始科目,不可编辑`, 'warning', 2000)
            }
        }
    }


    const firstLevelSubjectFunc = () => {

        FirstLevelSubjectPopupRef.current.show({
            args: {
                title: '快速新增一级科目',
                selectYear: AccountDataID
            },
            okCallback: () => {
                getSubjectListDatas(AccountDataID);
            }
        })
    }
    const relationMenuItems = (e: any) => {
        if (!TreeListRef.current) return;
        if (e?.target == 'content' && e?.row?.rowType == 'data') {
            console.log(e, e.row?.data, '@@@');
            if (!e.items) { e.items = [] };
            const rowData: any = e.row?.data;
            curNodeRef.current = e.row?.data;
            TreeListRef.current?.instance.selectRows(e.row.key);
            setCurRowKMMC(rowData.KMMC);

            const tempMenus = [
                {
                    text: "快速新增一级科目",
                    onItemClick: () => {
                        firstLevelSubjectFunc();
                    },
                },
                {
                    text: "增加科目",
                    onItemClick: () => {
                        console.log(rowData, '@@@ 增加科目');
                        // 判断 科目是否为一级
                        menuAddsubjectFunc(rowData);
                    },
                },
                {
                    text: "增加辅助账",
                    onItemClick: async () => {
                        const IsHasFZZ = await SubjectIsHasFZZ({
                            dbname,
                            Data_ID: AccountDataID,
                            KMBH: rowData.KMBH
                        });
                        const IsCanAddFZZState = await IsCanAddFZZ({
                            dbname,
                            Data_ID: AccountDataID,
                            KMBH: rowData.KMBH
                        });
                        console.log(IsHasFZZ, 'IsHasFZZ---');
                        // 判断 是否存在辅助账
                        if (IsHasFZZ[0].isExists) {
                            // 存在辅助账 判断是否可以增加辅助账
                            IsCanAddFZZStates(IsCanAddFZZState[0], true, rowData);
                        } else {
                            if (IsCanAddFZZState[0].code === 0) {
                                console.log("触发---");
                                notify(`${IsCanAddFZZState[0].message}`, 'warning', 2000);
                                return;
                            }
                            IsCanAddFZZStates(IsCanAddFZZState[0], false, rowData);
                        }
                    },
                },
                {
                    text: "编辑",
                    onItemClick: () => {
                        console.log(rowData, 'curNodeRef.current--------');
                        menuEditsubjectFunc(rowData);
                    },
                },
                {
                    text: "删除",
                    onItemClick: () => {

                        console.log(rowData, '@@@');
                        if (!rowData.isNewAdd) {
                            if (rowData.level === 99) {
                                return notify(`辅助账【${rowData.HSXMMC}】为企业原始辅助账,不可编辑`, 'warning', 2000)
                            }
                            if (rowData.level === 33) {
                                return notify(`科目【${rowData.KMMC}】为企业原始科目,不可编辑`, 'warning', 2000)
                            }
                        }
                        PhaseDeleteRef.current.show({
                            args: {
                                title: '询问',
                                codes: true,
                                Name: rowData.displayName,
                                HSXMLXBH: rowData.HSXMLXBH
                            },
                            okCallback: async () => {
                                if (rowData.HSXMLXBH) {
                                    // 删除 辅助账
                                    const r = await AssistDel({
                                        dbname,
                                        Data_ID: AccountDataID,
                                        KMBH: rowData.KMBH,
                                        editUser: username,
                                        HSXMLXBH: rowData.HSXMLXBH,
                                        HSXMBH: rowData.code + '~|'
                                    })
                                    if (!r.ok) {
                                        notify(`${r.data}`, 'warning', 2000)
                                    } else {
                                        notify('删除辅助账成功', 'success', 2000);
                                        getSubjectListDatas(AccountDataID);
                                    }
                                } else {
                                    // 删除 科目表
                                    const r = await SubjectDel({
                                        dbname,
                                        Data_ID: AccountDataID,
                                        editUser: username,
                                        KMBH: rowData.KMBH
                                    })
                                    if (r.ok) {
                                        notify('删除科目成功', 'success', 2000);
                                        getSubjectListDatas(AccountDataID);
                                    } else {
                                        notify(`${r.data}`, 'warning', 2000)
                                    }
                                }
                            },
                            cancelCallback: () => {
                            }
                        });
                    },
                },
            ];
            e.items.push(...tempMenus);
        }
    };







    const clickSelectNodeFun = useCallback(async (e: any) => {
        let tempObj = {};
        const arr = getChild(e.row?.node);
        const ars = deepClone(arr[0].data);
        let currentRow = TreeListRef.current.instance.getNodeByKey(ars?.ID);
        // 拿到所有父级节点的key
        const parentKeys = getAllParentData(currentRow);
        // 展开父级节点
        await TreeListRef.current.instance.option("expandedRowKeys", parentKeys);
        // 拿到子节点的第一项
        await TreeListRef.current.instance.selectRows(ars?.ID);
        tempObj = { ...ars, rowIndex: e.rowIndex };
        // const scrollable = TreeListRef.current.instance.getScrollable();
        // if (scrollable) {
        //     console.log(scrollable.scrollTop(), '@@@');
        //     
        //     setScrollTop(scrollable.scrollTop());
        //     scrollable.scrollTo({ top: scrollable.scrollTop() });
        // }
        return tempObj;
    }, []);
    const onCellDblClick = useCallback(async (e: any) => {
        console.log(e, ' @@@ onCellDblClick');
        if (e.rowType === "data" && e.row?.data?.ID) {
            const ars: any = await clickSelectNodeFun(e);
            if (!ars?.itemNames3) return notify("此科目未对应报表项目，请先对科目进行对应后，再进行调整", "error", 2000);
            const myId: guid = Guid.newGuid();
            let source8: any;
            let cellDbData: any = {};
            const source1 = ars;
            const source2 = { XH: e.rowIndex }; //序号
            const source3 = { DF: null }//贷方
            const source4 = { JF: null }; //借方
            const source5 = { remark: '' }; //备注
            const source6 = { GUID: myId }; //GUID
            const source7 = { billID: curDataBillID }; //billID
            if (whereFrom === '账表调整') {
                source8 = { isHCFSE: 0 }; //红冲
                cellDbData = Object.assign(source1, source2, source3, source4, source5, source7, source6, source8);
            } else {
                cellDbData = Object.assign(source1, source2, source3, source4, source5, source7, source6);
            };
            return treeNodeCellDblClick(cellDbData);

        }
    }, [curDataBillID]);



    const addSelectNode_fun = useCallback(async () => {
        const evert = TreeListRef.current.instance.getNodeByKey(startupSelectedKeys[0]);
        if (!evert) {
            return {};
        }
        let tempObj = {};
        const arr = getChild(evert);
        const ars = deepClone(arr[0].data);
        let currentRow = TreeListRef.current.instance.getNodeByKey(ars?.ID);
        // 拿到所有父级节点的key
        const parentKeys = getAllParentData(currentRow);
        // 展开父级节点
        await TreeListRef.current.instance.option("expandedRowKeys", parentKeys);
        // 拿到子节点的第一项
        await TreeListRef.current.instance.selectRows(ars?.ID);
        tempObj = { ...ars, rowIndex: 0 };
        // const scrollable = TreeListRef.current.instance.getScrollable();
        // if (scrollable) {
        //     console.log(scrollable.scrollTop(), '@@@');
        //     
        //     setScrollTop(scrollable.scrollTop());
        //     scrollable.scrollTo({ top: scrollable.scrollTop() });
        // }
        // 
        setStartupSelectedKeys([ars?.ID]);
        return tempObj;
    }, [startupSelectedKeys]);



    // 自定义方法
    useImperativeHandle(ref, () => ({
        addSelectNodeFun: async () => {
            return await addSelectNode_fun();
        },
    }));

    return (
        <div style={{ position: "relative", width: '100%', height: '100%', padding: '1px', display: 'flex', justifyContent: 'center', alignItems: 'center' }} className="leftTreeBox">

            {isShowRightTree && <div style={{
                position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: "center", justifyContent: "center",
                opacity: 0.5, zIndex: "99999", background: "#ddd"
            }}>
                <LoadIndicator id="medium-indicator" height={50} width={50} />
            </div>}

            {useMemo(() => {
                return <TreeList
                    className="PublicTreeList"
                    ref={TreeListRef}
                    allowColumnResizing={true}
                    showBorders={true}
                    showRowLines={true}
                    key={visiblePopupKey}
                    // 显示斑马线
                    rowAlternationEnabled={true}
                    dataSource={entryFilterTreeData}
                    selection={{
                        recursive: true,
                        mode: "single",
                    }}
                    parentIdExpr='PID'
                    keyExpr='ID'
                    rootValue='0'
                    id="ID"
                    width='calc(100% - 45px)'
                    height="100%"
                    defaultColumns={columns}
                    onContextMenuPreparing={relationMenuItems}
                    onCellDblClick={onCellDblClick}
                    onContentReady={(e) => {
                        setTimeout(() => {
                            setIsShowRightTree(false);
                        }, 1000);
                    }}
                    // loadPanel={{
                    //     enabled: true,
                    //     text: 'Loading...',
                    // }}
                    onSelectionChanged={(e) => {
                        // console.log(e, "触发----------");
                        const { selectedRowKeys } = e;
                        console.log(selectedRowKeys, e, "触发----------");
                        // setSelectState(false);
                        setStartupSelectedKeys(selectedRowKeys);
                        treeSelectCellClick({ selectionType: "onSelection", ID: selectedRowKeys[0] });
                    }}
                    // onCellClick={async (e: any) => {
                    //     if (e.rowType === "data" && e.row?.data?.ID) {
                    //         const ars = await clickSelectNodeFun(e);
                    //         return treeSelectCellClick(ars);
                    //     }
                    // }}
                    searchPanel={{
                        visible: true,
                        width: 180,
                        placeholder: '',
                    }}
                    toolbar={{
                        items: [
                            {
                                cssClass: 'searchPanel_Style',
                                location: 'after',
                                name: 'searchPanel',
                            },
                            {
                                location: 'after',
                                widget: 'dxButton',
                                cssClass: 'refreshButton_Style',
                                options: {
                                    icon: "iconfont icon-refresh",
                                    onClick: () => {
                                        getSubjectListDatas(AccountDataID);
                                    },
                                },
                            },
                        ],
                    }}
                />
            }, [entryFilterTreeData, visiblePopupKey])}
            <HocVerticalLeftStyleTab
                activeKey={tbsStates}
                className='AccountSubjectsTabs'
                tabPosition='left'
                tabBarStyle={{ background: '#FFF' }}
                onChange={(e: any) => {

                    console.log(e, 'e @@@');

                    getSubjectListData(e || '0', true)
                }}
            >
                {Array.isArray(entryTabsData) ?
                    entryTabsData.map((item: any) => {
                        return <AntTabs.Panel
                            tab={item.type}
                            key={item.code}
                            style={{ marginTop: "5px" }}
                        />
                    })
                    : <></>
                }
            </HocVerticalLeftStyleTab >
            <PhaseDeleteDialog ref={PhaseDeleteRef} />
            <SubjectPopupData ref={SubjectPopupRef} AccountDataID={AccountDataID} />
            <FirstLevelSubjectPopup ref={FirstLevelSubjectPopupRef} AccountDataID={AccountDataID} />
            <AuxiliaryPopup ref={AuxiliaryPopupRef} AccountDataID={AccountDataID} />
            <DevPopup.Default ref={TreeAuxiliaryRef}>
                {() => {
                    return <span>{`${AddFZZKMMC}`}</span>
                }}
            </DevPopup.Default>
            <DevPopup.Default ref={typeRef}>
                {() => {
                    return <span>{`【${curRowKMMC}】为末级科目，是否继续为其增加下级科目？`}</span>;
                }}
            </DevPopup.Default>
            <DevPopup.Default ref={typeErrorRef}>
                {() => {
                    return <>
                        <span>{`【${curRowKMMC}】`}</span>
                        <span style={{ color: "red" }} >为末级科目，已被设置辅助账，无法增加下级科目!</span>
                    </>
                }}
            </DevPopup.Default>
        </div>
    )
});

export default AdjustLeftTree;
